/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import com.lowagie.text.Image;
import dao.*;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;
import model.*;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
import sun.security.x509.AttributeNameEnumeration;

/**
 * CADASTRO PADRÃO
 *
 * @author JONATAS
 *
 *
 */
public class MaterialFrameTab1 extends javax.swing.JFrame {

    /**
     * Creates new form FamiliaFrame
     */
    public MaterialFrameTab1() {
        initComponents();
        setStatusInicial();
        buscarClassesCB();
        buscarUnidadesMedidaCB();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        btnDeletar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        btnCancelar = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel5 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        lbFoto = new javax.swing.JLabel();
        tbCaminhoImg = new javax.swing.JTextField();
        btnImagem = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        tbCodigo = new javax.swing.JTextField();
        tbDescricao = new javax.swing.JTextField();
        cmbClasse = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        cmbFamilia = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        cmbUnidadeMedida = new javax.swing.JComboBox();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel7 = new javax.swing.JLabel();
        btnAddProdutos = new javax.swing.JButton();
        btnExlcuirProdutoComp = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem12 = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem8 = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jMenuItem9 = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem10 = new javax.swing.JMenuItem();
        Relatório = new javax.swing.JMenu();
        jMenuItem13 = new javax.swing.JMenuItem();
        jMenuItem14 = new javax.swing.JMenuItem();
        jMenuItem15 = new javax.swing.JMenuItem();
        jMenuItem16 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem7 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Materiais");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                buscar(evt);
            }
        });

        btnDeletar.setText("Deletar");
        btnDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletarActionPerformed(evt);
            }
        });

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Classe", "Familia", "Descrição", "Unid. Medida"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setNextFocusableComponent(btnSalvar);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTable1MouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.setName("");
        btnSalvar.setNextFocusableComponent(cmbClasse);
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        lbFoto.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lbFoto.setText("Sem imagem selecionada");
        lbFoto.setToolTipText("");
        lbFoto.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        lbFoto.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        lbFoto.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        lbFoto.setMaximumSize(new java.awt.Dimension(500, 500));
        lbFoto.setMinimumSize(new java.awt.Dimension(500, 500));

        tbCaminhoImg.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tbCaminhoImgFocusLost(evt);
            }
        });

        btnImagem.setText("Imagem...");
        btnImagem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnImagemActionPerformed(evt);
            }
        });
        btnImagem.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                btnImagemFocusLost(evt);
            }
        });

        jLabel4.setText("Imagem:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel3Layout.createSequentialGroup()
                                .addComponent(btnImagem)
                                .addContainerGap())
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(tbCaminhoImg, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(lbFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(165, 165, 165))))))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbFoto, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(tbCaminhoImg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnImagem)
                .addGap(20, 20, 20))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        jLabel1.setText("Código:");

        jLabel2.setText("Descrição: ");

        tbCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbCodigoActionPerformed(evt);
            }
        });

        tbDescricao.setNextFocusableComponent(cmbUnidadeMedida);
        tbDescricao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tbDescricaoActionPerformed(evt);
            }
        });
        tbDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbDescricaoKeyPressed(evt);
            }
        });

        cmbClasse.setFocusCycleRoot(true);
        cmbClasse.setNextFocusableComponent(cmbFamilia);
        cmbClasse.setOpaque(false);
        cmbClasse.setRequestFocusEnabled(false);
        cmbClasse.setVerifyInputWhenFocusTarget(false);
        cmbClasse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbClasseActionPerformed(evt);
            }
        });
        cmbClasse.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbClasseKeyPressed(evt);
            }
        });

        jLabel5.setText("Classe:");

        cmbFamilia.setFocusCycleRoot(true);
        cmbFamilia.setNextFocusableComponent(tbDescricao);
        cmbFamilia.setOpaque(false);
        cmbFamilia.setRequestFocusEnabled(false);
        cmbFamilia.setVerifyInputWhenFocusTarget(false);
        cmbFamilia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFamiliaActionPerformed(evt);
            }
        });
        cmbFamilia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbFamiliaKeyPressed(evt);
            }
        });

        jLabel6.setText("Família");

        jLabel8.setText("Unidade de Medida:");

        cmbUnidadeMedida.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Selecione uma Marca" }));
        cmbUnidadeMedida.setOpaque(false);
        cmbUnidadeMedida.setRequestFocusEnabled(false);
        cmbUnidadeMedida.setVerifyInputWhenFocusTarget(false);
        cmbUnidadeMedida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbUnidadeMedidaActionPerformed(evt);
            }
        });
        cmbUnidadeMedida.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cmbUnidadeMedidaKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                cmbUnidadeMedidaKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                cmbUnidadeMedidaKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tbDescricao)
                    .addComponent(cmbUnidadeMedida, 0, 460, Short.MAX_VALUE)
                    .addComponent(cmbFamilia, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cmbClasse, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel1)
                            .addComponent(jLabel8)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5)
                            .addComponent(tbCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 288, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tbCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbClasse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbFamilia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(tbDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addComponent(jLabel8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmbUnidadeMedida, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(57, 57, 57))
        );

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(22, 22, 22)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        jTabbedPane1.addTab("Enquadramento e Identificação do Material", jPanel5);

        jPanel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Descrição", "Classe", "Familia", "Unidade Medida", "Quantidade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setColumnSelectionAllowed(true);
        jScrollPane2.setViewportView(jTable2);
        jTable2.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jLabel7.setText("Composição: ");

        btnAddProdutos.setText("Adicionar Produto");
        btnAddProdutos.setEnabled(false);
        btnAddProdutos.setNextFocusableComponent(btnSalvar);
        btnAddProdutos.setOpaque(false);
        btnAddProdutos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddProdutosActionPerformed(evt);
            }
        });

        btnExlcuirProdutoComp.setText("Excluir Produto");
        btnExlcuirProdutoComp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExlcuirProdutoCompActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnExlcuirProdutoComp)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAddProdutos))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 887, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddProdutos)
                    .addComponent(btnExlcuirProdutoComp))
                .addGap(4, 4, 4))
        );

        jTabbedPane1.addTab("Composição", jPanel4);

        jLabel9.setText("Produtos Cadastrados:");

        jMenu1.setText("Cadastros");

        jMenuItem1.setText("Clientes");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem12.setText("Usuários");
        jMenuItem12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem12ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem12);
        jMenu1.add(jSeparator3);

        jMenuItem2.setText("Casses");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setText("Famílias");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem3);

        jMenuItem8.setText("Produtos");
        jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem8ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem8);
        jMenu1.add(jSeparator1);

        jMenuItem9.setText("Localização");
        jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem9ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem9);
        jMenu1.add(jSeparator2);

        jMenuItem4.setText("Sair");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem4);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Projetos");

        jMenuItem5.setText("Gerenciar Projetos");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        jMenuItem6.setText("Consultar Projetos");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem6);

        jMenuItem10.setText("Imprimir Documento");
        jMenu2.add(jMenuItem10);

        jMenuBar1.add(jMenu2);

        Relatório.setText("Relatórios");

        jMenuItem13.setText("Relatório de Classes/Famílias");
        Relatório.add(jMenuItem13);

        jMenuItem14.setText("Relatório de Materiais");
        Relatório.add(jMenuItem14);

        jMenuItem15.setText("Relatório de Projetos");
        Relatório.add(jMenuItem15);

        jMenuItem16.setText("Relatório de Clientes");
        Relatório.add(jMenuItem16);

        jMenuBar1.add(Relatório);

        jMenu4.setText("Sobre");
        jMenuBar1.add(jMenu4);

        jMenu3.setText("Sair");

        jMenuItem7.setText("Sair");
        jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem7ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem7);

        jMenuBar1.add(jMenu3);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 918, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnSalvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnDeletar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnDeletar)
                    .addComponent(btnCancelar)
                    .addComponent(btnSalvar))
                .addGap(17, 17, 17))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-960)/2, (screenSize.height-882)/2, 960, 882);
    }// </editor-fold>//GEN-END:initComponents

    private void setStatusInicial() {

        status = 'I';
        tbCodigo.setText("Novo Registro");
        btnDeletar.setEnabled(false);
        cmbClasse.setEnabled(true);
        cmbFamilia.setEnabled(true);
        cmbClasse.requestFocus();
        //cmbFamilia.setEnabled(false);
        jTabbedPane1.setEnabledAt(1, false);
        jTabbedPane1.setSelectedIndex(0);
        btnAddProdutos.setFocusable(false);

    }

    private void setStatusAlterar() {

        status = 'A';
        cmbClasse.setEnabled(false);
        cmbFamilia.setEnabled(false);
        btnDeletar.setEnabled(true);
    }

    private void limparCampos() {
        tbCodigo.setText("");
        tbDescricao.setText("");
        cmbClasse.setSelectedIndex(0);
        //cmbFamilia.setSelectedIndex(1);
        cmbUnidadeMedida.setSelectedIndex(0);
        tbCaminhoImg.setText("");
        carregarImagem(tbCaminhoImg.getText());

    }

    private boolean verificaCamposNulos() {
        if (tbDescricao.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Campo descrição em branco!");
            tbDescricao.requestFocus();
            return false;
        }
        if (cmbClasse.getSelectedIndex() == 0) {
            JOptionPane.showMessageDialog(null, "Selecione uma classe!");
            cmbClasse.requestFocus();
            return false;
        }
        if (cmbFamilia.getSelectedIndex() == 0) {
            JOptionPane.showMessageDialog(null, "Selecione uma familia!");
            cmbFamilia.requestFocus();
            return false;
        }
        if (cmbUnidadeMedida.getSelectedIndex() == 0) {
            JOptionPane.showMessageDialog(null, "Selecione uma unidade de medida!");
            cmbUnidadeMedida.requestFocus();
            return false;
        }

        return true;

    }
    private void tbCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tbCodigoActionPerformed

    private void tbDescricaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tbDescricaoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tbDescricaoActionPerformed

    private void buscar(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_buscar
        buscarTodos();
    }//GEN-LAST:event_buscar

    private void buscarTodos() {
        // Carrega todos os dados da tabela Familia 
        List<Material> lista = new MaterialDAO().findAll();

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);



        for (Material mat : lista) {
            modelo.addRow(new String[]{mat.getMat_classe().getCla_id() + mat.getMat_familia().getFam_id() + mat.getMat_identificador() + "-" + mat.getMat_digitoVerificador() + "", "" + mat.getMat_classe().getCla_descricao(), mat.getMat_familia().getFam_descricao(), mat.getMat_descricao(), mat.getMat_unidadeMedida().getUnm_descricao()});
        }
    }

    private void carregarMateriaisDoProduto(Material id) {

        List<MaterialDoProduto> lista = new MaterialDoProdutoDAO().findMateriaisDoProduto(id);
        DefaultTableModel modelo = (DefaultTableModel) jTable2.getModel();
        modelo.setNumRows(0);

        for (MaterialDoProduto m : lista) {
            modelo.addRow(new String[]{"" + m.getMaterialComponente().getMat_codigoCompleto(), m.getMaterialComponente().getMat_descricao(), m.getMaterialComponente().getMat_classe().getCla_descricao(), m.getMaterialComponente().getMat_familia().getFam_descricao(), m.getMaterialComponente().getMat_unidadeMedida().getUnm_sigla(), m.getQuantidade() + ""});
        }
    }

    private void selecionar() {

        // obtem o valor da linha selecionada
        int selecionada = jTable1.getSelectedRow();

        // obtem o valor da coluna
        String codigo = (String) jTable1.getValueAt(selecionada, 0);

        String classe = codigo.substring(0, 2);
        String familia = codigo.substring(2, 4);
        String id_material = codigo.substring(4, 11);
        System.out.println("classe: " + classe);
        System.out.println("familia: " + familia);
        System.out.println("material: " + id_material);

        System.out.println("Selecionou Familia id -> " + codigo);

        mat = new Material();
        mat.setMat_identificador(id_material);

        System.out.println("1A: ");
        Familia fid = new Familia();
        System.out.println("2A: ");
        fid.setFam_id(familia);
        mat.setMat_familia(fid);
        System.out.println("3A: ");

        System.out.println("4A: " + codigo.substring(0, 11) + codigo.substring(12, 13));
        mat = mdao.findByIdComposta(codigo.substring(0, 11) + codigo.substring(12, 13));
        System.out.println("5A: " + mat.getMat_id());

        tbDescricao.setText(mat.getMat_descricao());
        cmbClasse.getModel().setSelectedItem(mat.getMat_classe());
        cmbFamilia.getModel().setSelectedItem(mat.getMat_familia());
        cmbUnidadeMedida.getModel().setSelectedItem(mat.getMat_unidadeMedida());
        tbCaminhoImg.setText(mat.getMat_imagem());
        tbCodigo.setText(mat.getMat_classe().getCla_id() + mat.getMat_familia().getFam_id() + mat.getMat_identificador() + mat.getMat_digitoVerificador());
        carregarImagem(mat.getMat_imagem());
        if (mat.getMat_classe().getProdutoIntermediario() == 1) {
            MaterialDoProduto mp = new MaterialDoProduto();
            mp.setMaterialPai(mat);
            carregarMateriaisDoProduto(mp.getMaterialPai());
            //jTabbedPane1.setEnabledAt(0, true);            
        } else {
            jTabbedPane1.setSelectedIndex(0);
        }
        System.out.println("5A: ");
        setStatusAlterar();
    }

    private void buscarClassesCB() {

        //List<Marca> lista = new MarcaDAO().findAll();        
        Vector v = new Vector();
        v.add(0, "Selecione uma Classe");
        Vector vt = new Vector(new ClasseDAO().findAll());
        Vector vmodel = new Vector();

        int i = 0;
        for (i = 0; i < 1; i++) {
            System.out.println("Set pos " + i);
            vmodel.add(i, v.get(i));
            System.out.println("Set pos " + i);
        }
        for (int l = 0; l < vt.size(); l++) {
            vmodel.add(i, vt.get(l));
            System.out.println("Set pos " + i);
            i++;
        }

        DefaultComboBoxModel cmodel = new DefaultComboBoxModel(vmodel);
        cmbClasse.setModel(cmodel);

    }

    private void buscarFamiliasCB(String cla_id) {

        Vector v = new Vector();
        v.add(0, "Selecione uma Família");
        Vector vt = new Vector(new FamiliaDAO().findByClasse(cla_id));
        Vector vmodel = new Vector();

        int i = 0;
        for (i = 0; i < 1; i++) {
            System.out.println("Set pos " + i);
            vmodel.add(i, v.get(i));
            System.out.println("Set pos " + i);
        }
        for (int l = 0; l < vt.size(); l++) {
            vmodel.add(i, vt.get(l));
            System.out.println("Set pos " + i);
            i++;
        }

        DefaultComboBoxModel fmodel;
        fmodel = new DefaultComboBoxModel(vmodel);


        cmbFamilia.setModel(fmodel);

        /*
         * if (cmbFamilia.getModel().getSize() > 0) { Familia f = (Familia)
         * cmbFamilia.getModel().getSelectedItem();
         * tbCodigo.setText(f.getFam_classe().getCla_id() + f.getFam_id() +
         * mdao.getCode(f.getFam_id())); } else if
         * (cmbClasse.getModel().getSize() > 0) { Classe c = (Classe)
         * cmbClasse.getModel().getSelectedItem();
         * tbCodigo.setText(c.getCla_id() + ""); }
         */

    }

    private void buscarUnidadesMedidaCB() {
        //List<Marca> lista = new MarcaDAO().findAll();        

        Vector v = new Vector();
        v.add(0, "Selecione uma Unidade de Medida");
        Vector vt = new Vector(new UnidadeMedidaDAO().findAll());
        Vector vmodel = new Vector();

        int i = 0;
        for (i = 0; i < 1; i++) {
            System.out.println("Set pos " + i);
            vmodel.add(i, v.get(i));
            System.out.println("Set pos " + i);
        }
        for (int l = 0; l < vt.size(); l++) {
            vmodel.add(i, vt.get(l));
            System.out.println("Set pos " + i);
            i++;
        }

        DefaultComboBoxModel cmodel = new DefaultComboBoxModel(vmodel);
        cmbUnidadeMedida.setModel(cmodel);

    }

    private void btnDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletarActionPerformed

        //  Classe m = dao.findById( Integer.parseInt(tbCodigo.getText()) ); 
        int opt;

        switch (status) {
            case 'D': // Ação de deletar mais de uma linha ao mesmo tempo

                opt = JOptionPane.showConfirmDialog(null, "Deseja excluir os materiais selecionados? ");
                System.out.println("Option = -> " + opt);
                if (opt == 0) {
                    int[] selecionadas = jTable1.getSelectedRows();
                    Familia f = new Familia();
                    String codigo;


                    for (int i = 0; i < jTable1.getSelectedRowCount(); i++) { // Apaga linha por linha selecionada

                        mat = new Material();
                        System.out.println(i + "a. de " + jTable1.getSelectedRowCount() + "Linha select -> " + selecionadas[i]);

                        codigo = (String) jTable1.getValueAt(selecionadas[i], 0);

                        f.setFam_id(codigo.substring(2, 4));
                        mat.setMat_familia(f);
                        mat.setMat_id(codigo.substring(4, 11));

                        System.out.println("Selecionou Familia id -> " + codigo);

                        mat = mdao.findByIdComposta(mat.getMat_id());
                        mpdao.deleteMateriaisDoProduto(mat);
                        mdao.delete(mat);
                    }
                    buscar(null);
                    limparCampos();
                    setStatusInicial();
                } /*
                 * else { setStatusInicial();
                }
                 */
                break;
            case 'A': // Deletar uma linha 
                opt = JOptionPane.showConfirmDialog(null, "Deseja excluir o material selecionado? ");
                System.out.println("Option = -> " + opt);
                if (opt == 0) {
                    try {
                        mpdao.deleteMateriaisDoProduto(mat);                        
                        mdao.delete(mat);
                        buscar(null);
                        limparCampos();
                        setStatusInicial();
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "Não é possível deletar este material, pois o mesmo está sendo usado em algum projeto. ");
                    }
                }/*
                 * else { setStatusInicial();
                }
                 */
                break;
        }
    }//GEN-LAST:event_btnDeletarActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked

        selecionar();
        tbDescricao.requestFocus();

    }//GEN-LAST:event_jTable1MouseClicked

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        limparCampos();
        buscarTodos();
        setStatusInicial();
        carregarMateriaisDoProduto(null);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void tbDescricaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbDescricaoKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) { //  Se pressionar enter éo mesmo que clicar no botao salvar
            btnSalvarActionPerformed(null);
        }
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { // Se pressionar ESQ é o mesmo que Cancelar
            btnCancelarActionPerformed(null);
        }


        /*
         * Exemplo para usar um DIALOG
         *
         * if (evt.getKeyCode() == KeyEvent.VK_F2) { // Se pressionar F2
         * seleciona ClasseDialog cd = new ClasseDialog(null, true);
         * cd.setVisible(true); tbCodigo.setText(cd.getClasse().getCla_id()+"");
         * tbDescricao.setText(cd.getClasse().getCla_descricao());
         * setStatusAlterar(); }
         */
    }//GEN-LAST:event_tbDescricaoKeyPressed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed

        switch (status) {
            case 'I': // Status de  Inserir

                mat = new Material();

                Familia fam = (Familia) cmbFamilia.getSelectedItem();
                fam = new FamiliaDAO().findById(fam.getFam_id());

                mat.setMat_familia(fam);
                mat.getMat_familia().setFam_classe((Classe) cmbClasse.getSelectedItem());
                mat.setMat_descricao(tbDescricao.getText());
                mat.setMat_imagem(tbCaminhoImg.getText());
                mat.setMat_unidadeMedida((UnidadeMedida) cmbUnidadeMedida.getSelectedItem());

                // O retorno do verifica  campos nulos é TRUE ou FALSE - dápra usar direto no IF
                if (verificaCamposNulos()) {

                    mat.setMat_identificador(mdao.getCode(mat.getMat_familia().getFam_id()));
                    System.out.println(mat.getMat_classe().getCla_id() + mat.getMat_familia().getFam_id() + mat.getMat_identificador());
                    mat.setMat_digitoVerificador(mat.gerarDigitoVerificador(mat.getMat_classe().getCla_id() + mat.getMat_familia().getFam_id() + mat.getMat_identificador()));
                    mat.setMat_id(mat.getMat_classe().getCla_id() + mat.getMat_familia().getFam_id() + mat.getMat_identificador() + mat.getMat_digitoVerificador() + "");
                    mdao.insert(mat);
                    mdao.Commit();
                    System.out.println("commit mat principal");

                    if (mat.getMat_familia().getFam_classe().getProdutoIntermediario() == 1) {

                        for (int i = 0; i < jTable2.getRowCount(); i++) {

                            mp = new MaterialDoProduto();
                            System.out.println("linha da tabela -> " + i);
                            System.out.println("contagem de linhas -> " + jTable2.getRowCount());

                            Material mc = new Material();

                            mc.setMat_codigoCompleto(jTable2.getValueAt(i, 0).toString());


                            System.out.println("Codigo completo produto componente: GetValue " + jTable2.getValueAt(i, 0).toString());

                            mp.setMaterialComponente(mc);
                            System.out.println("Componente: mc.gets " + mc.getMat_codigoCompleto() + " " + mc.getMat_familia().getFam_descricao() + " id -> " + mc.getMat_identificador());
                            mp.setMaterialPai(mat);
                            System.out.println("Pai: mat pai.gets " + mat.getMat_codigoCompleto() + " " + mat.getMat_familia().getFam_descricao() + " id -> " + mat.getMat_identificador());
                            mp.setQuantidade(Integer.parseInt(jTable2.getValueAt(i, 5).toString()));
                            System.out.println("Quantidade:  " + jTable2.getValueAt(i, 5).toString());

                            System.out.println("Revisao MP codigo completo componente-> " + mp.getMaterial_produto_id().getMaterialComponente().getMat_codigoCompleto());
                            System.out.println("Revisao MP codigo completo pai -> " + mp.getMaterialPai().getMat_codigoCompleto());
                            System.out.println("Revisao MP quantidade-> " + mp.getQuantidade());

                            mpdao.insert(mp);
                            System.out.println("Insert mp componente");

                        }
                        mpdao.Commit();
                        System.out.println("commit mat princ");

                    }
                    JOptionPane.showMessageDialog(null, "Material inserido com sucesso! Código Gerado -> " + mat.getMat_classe().getCla_id() + mat.getMat_familia().getFam_id() + mat.getMat_identificador());
                    buscarTodos();
                    limparCampos();
                    setStatusInicial();
                }
                break;
            case 'A': // Status de Alterar

                mat.setMat_descricao(tbDescricao.getText());
                mat.setMat_imagem(tbCaminhoImg.getText());
                mat.setMat_unidadeMedida((UnidadeMedida) cmbUnidadeMedida.getSelectedItem());

                if (verificaCamposNulos()) {

                    mdao.update(mat);
                    // mpdao.deleteMateriaisDoProduto(mat);
                    Material mc = new Material();

                    if (mat.getMat_familia().getFam_classe().getProdutoIntermediario() == 1) {
                        for (int i = 0; i < jTable2.getRowCount(); i++) {

                            System.out.println("linha da tabela -> " + i);
                            System.out.println("contagem de linhas -> " + jTable2.getRowCount());

                            mp = new MaterialDoProduto();
                            mc = new Material();

                            mc.setMat_codigoCompleto(jTable2.getValueAt(i, 0).toString());

                            System.out.print("ID PK->" + mp.getMaterial_produto_id());
                            System.out.println("Codigo completo produto componente: GetValue " + jTable2.getValueAt(i, 0).toString());

                            mp.setMaterialComponente(mc);
                            System.out.println("Componente: mc.gets " + mc.getMat_codigoCompleto() + " " + mc.getMat_familia().getFam_descricao() + " id -> " + mc.getMat_identificador());

                            mp.setMaterialPai(mat);
                            System.out.println("Pai: mat pai.gets " + mat.getMat_codigoCompleto() + " " + mat.getMat_familia().getFam_descricao() + " id -> " + mat.getMat_identificador());

                            mp.setQuantidade(Integer.parseInt(jTable2.getValueAt(i, 5).toString()));
                            System.out.println("Quantidade:  " + jTable2.getValueAt(i, 5).toString());

                            System.out.println("Revisao MP codigo completo componente-> " + mp.getMaterial_produto_id().getMaterialComponente().getMat_codigoCompleto());
                            System.out.println("Revisao MP codigo completo pai -> " + mp.getMaterialPai().getMat_id());
                            System.out.println("Revisao MP quantidade-> " + mp.getQuantidade());

                            mpdao.merge(mp);

                            System.out.println("Insert mp componente");
                        }
                        mpdao.Commit();
                        System.out.println("commit mat princ");

                    }
                    buscarTodos();
                    limparCampos();
                    setStatusInicial();
                    break;
                }
        }


    }//GEN-LAST:event_btnSalvarActionPerformed

    private void jTable1MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseReleased

        /*
         * Quando o usuário seleciona várias linhas o sistema permite deletar
         * todas de uma vez
         */
        limparCampos();
        status = 'D';
        btnDeletar.setEnabled(true);

    }//GEN-LAST:event_jTable1MouseReleased

    private void cmbClasseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbClasseActionPerformed

        if (cmbClasse.getSelectedIndex() != 0) {
            cla = new Classe();
            cla = (Classe) cmbClasse.getSelectedItem();
            System.out.println("Cla_id da classe sleecionada -> " + cla.getCla_id());
            buscarFamiliasCB(cla.getCla_id());
            if (cla.getProdutoIntermediario() == 1) {
                jTabbedPane1.setEnabledAt(1, true);
                btnAddProdutos.setEnabled(true);
            } else {
                jTabbedPane1.setEnabledAt(1, false);
                btnAddProdutos.setEnabled(false);
            }
        } else {
            buscarFamiliasCB(null);
        }
    }//GEN-LAST:event_cmbClasseActionPerformed

    private void cmbClasseKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbClasseKeyPressed
        /*
         * if (evt.getKeyCode() == KeyEvent.VK_ENTER) { // Se pressionar enter
         * éo mesmo que clicar no botao salvar btnSalvarActionPerformed(null); }
         */
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) { // Se pressionar ESQ é o mesmo que Cancelar
            btnCancelarActionPerformed(null);
        }

    }//GEN-LAST:event_cmbClasseKeyPressed

    private void cmbFamiliaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFamiliaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbFamiliaActionPerformed

    private void cmbFamiliaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbFamiliaKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbFamiliaKeyPressed

    private void cmbUnidadeMedidaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbUnidadeMedidaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbUnidadeMedidaActionPerformed

    private void cmbUnidadeMedidaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbUnidadeMedidaKeyPressed
    }//GEN-LAST:event_cmbUnidadeMedidaKeyPressed

    private void btnImagemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImagemActionPerformed

        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Selecione uma imagem");
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        //
        // disable the "All files" option.
        //
        chooser.setAcceptAllFileFilterUsed(false);
        //    
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            System.out.println("getCurrentDirectory(): "
                    + chooser.getCurrentDirectory());
            System.out.println("getSelectedFile() : "
                    + chooser.getSelectedFile());
        } else {
            System.out.println("No Selection ");
        }
        carregarImagem(chooser.getSelectedFile() + "");
    }//GEN-LAST:event_btnImagemActionPerformed

    private void tbCaminhoImgFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tbCaminhoImgFocusLost
        carregarImagem(tbCaminhoImg.getText());
    }//GEN-LAST:event_tbCaminhoImgFocusLost

    private void cmbUnidadeMedidaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbUnidadeMedidaKeyTyped
    }//GEN-LAST:event_cmbUnidadeMedidaKeyTyped

    private void cmbUnidadeMedidaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cmbUnidadeMedidaKeyReleased
    }//GEN-LAST:event_cmbUnidadeMedidaKeyReleased

    private void btnAddProdutosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddProdutosActionPerformed

        ProdutosComponentesDialog popup = new ProdutosComponentesDialog(this, true);
        popup.setVisible(true);

        Material m = new Material();
        m = popup.getMaterialComponente();

        System.out.println("AQUIIII!");
        DefaultTableModel modelo = (DefaultTableModel) jTable2.getModel();

        modelo.addRow(new String[]{"" + m.getMat_codigoCompleto(), m.getMat_descricao(), m.getMat_classe().getCla_descricao(), m.getMat_unidadeMedida().getUnm_sigla(), m.getMat_familia().getFam_descricao(), "1"});

        popup.dispose();

    }//GEN-LAST:event_btnAddProdutosActionPerformed

    private void btnExlcuirProdutoCompActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExlcuirProdutoCompActionPerformed
        int selecionada = jTable2.getSelectedRow();
        // obtem o valor da coluna
        String codigo = (String) jTable2.getValueAt(selecionada, 0);

        DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
        model.removeRow(jTable2.getSelectedRow());
        jTable2.setModel(model);

        //jTable2.remove(jTable2.getSelectedRow());
        /*
         * Material mater = new Material(); mater.setMat_codigoCompleto(codigo);
         * MaterialDoProduto mp = new MaterialDoProduto();
         * mp.setMaterialPai(mat); mp.setMaterialComponente(mater);
         *
         * MaterialDoProdutoDAO mpdao = new MaterialDoProdutoDAO();
         */
    }//GEN-LAST:event_btnExlcuirProdutoCompActionPerformed

    private void btnImagemFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_btnImagemFocusLost
        Classe cl = (Classe) cmbClasse.getModel().getSelectedItem();

        if (cl.getProdutoIntermediario() == 1) {
            jTabbedPane1.setEnabledAt(1, true);
            jTabbedPane1.setSelectedIndex(1);
            btnAddProdutos.setFocusable(true);
            btnAddProdutos.requestFocus();
        } else {
            btnSalvar.requestFocus();
        }
    }//GEN-LAST:event_btnImagemFocusLost

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        ClienteFrame cf = new ClienteFrame();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem12ActionPerformed
        UsuarioFrame cf = new UsuarioFrame();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem12ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        ClasseFrame cf = new ClasseFrame();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        FamiliaFrame cf = new FamiliaFrame();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
        MaterialFrameTab1 cf = new MaterialFrameTab1();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem8ActionPerformed

    private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
        LocalizaFrame cf = new LocalizaFrame();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem9ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
        System.exit(1);
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
        ProjetoFrame cf = new ProjetoFrame();
        cf.setVisible(true);
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
   }//GEN-LAST:event_jMenuItem6ActionPerformed

    private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
        System.exit(1);
    }//GEN-LAST:event_jMenuItem7ActionPerformed

    private void carregarImagem(String diretorio) {

        ImageIcon im = new ImageIcon();
        if (!diretorio.isEmpty()) {
            im = (new javax.swing.ImageIcon(diretorio));
            java.awt.Image i = im.getImage();
            i = i.getScaledInstance(lbFoto.getWidth(), lbFoto.getHeight(), 0);
            //lbFoto.setIcon(new javax.swing.ImageIcon(chooser.getSelectedFile()+"")); // NOI18N 
            im.setImage(i);
            tbCaminhoImg.setText(diretorio);
        }
        lbFoto.setIcon(im);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MaterialFrameTab1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MaterialFrameTab1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MaterialFrameTab1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MaterialFrameTab1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MaterialFrameTab1().setVisible(true);
            }
        });
    }
    private char status = 'I'; /*
     * I -> Inserir A -> Alterar D-> DELETAR INTERVALO
     */

    private Material mat = new Material();
    private MaterialDAO mdao = new MaterialDAO();
    private MaterialDoProduto mp = new MaterialDoProduto();
    private MaterialDoProdutoDAO mpdao = new MaterialDoProdutoDAO();
    private Classe cla = new Classe();
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu Relatório;
    private javax.swing.JButton btnAddProdutos;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnDeletar;
    private javax.swing.JButton btnExlcuirProdutoComp;
    private javax.swing.JButton btnImagem;
    private javax.swing.JButton btnSalvar;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cmbClasse;
    private javax.swing.JComboBox cmbFamilia;
    private javax.swing.JComboBox cmbUnidadeMedida;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem10;
    private javax.swing.JMenuItem jMenuItem12;
    private javax.swing.JMenuItem jMenuItem13;
    private javax.swing.JMenuItem jMenuItem14;
    private javax.swing.JMenuItem jMenuItem15;
    private javax.swing.JMenuItem jMenuItem16;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JMenuItem jMenuItem7;
    private javax.swing.JMenuItem jMenuItem8;
    private javax.swing.JMenuItem jMenuItem9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JLabel lbFoto;
    private javax.swing.JTextField tbCaminhoImg;
    private javax.swing.JTextField tbCodigo;
    private javax.swing.JTextField tbDescricao;
    // End of variables declaration//GEN-END:variables
}
